<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Area;
use app\admin\model\Operator;
use app\admin\model\Member;
use app\admin\model\Article;

use think\Db;
use think\Request;

class Villages extends Base
{
    public function _initialize() {
        parent::_initialize();
        $this->model = 'villages';
        $this->redirect = 'admin/village/index';

        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;

        if($this->admin->villageId){
            $this->error('您没有访问权限！');
        }
    }

    public function index(){
        return parent::index();
    }

    public function add(Request $request){
        return parent::add($request);
    }

    public function addPost(Request $request, $redirect='') {
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();
            // Insert data
            $data['id'] = BaseHelper::getUUID();
            $data['createDate'] = time();
            $data['createOper'] = $this->admin->id;
            $data['imgUrl'] = $data['coverImg'];
            $result = $model->save($data);

            if($result !== false) {
                // 单图
                if(isset($data['imgId']) && !empty($data['imgId'])){
                    Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages']);
                }
                // 多图
                if(isset($data['imgIds']) && !empty($data['imgIds'])){
                    foreach ((array)$data['imgIds'] as $key => $item) {
                        Image::where('id', $item)->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                // 详情图
                if(isset($data['detailImgIds']) && !empty($data['detailImgIds'])){
                    foreach ((array)$data['detailImgIds'] as $detailImgId) {
                        Image::where('id', $detailImgId)->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages']);
                    }
                }

                // Query执行后的操作
                $model->_after_insert($data);

                // 写入日志
                $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('添加成功！', $redirect);
                } else {
                    return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('');
        }
    }

    public function edit(Request $request) {
        $model = model($this->model);
        $id = $request->param('id');
        $info = $model->where('id',$id)->find();
        // dump($info);die;
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        // 图集
        $imagesList = Image::where(['relatedId' => $info->id, 'tag' => 'imglist'])->where('imgUrl', 'neq', $info->imgUrl)->order('sorting ASC')->select();
        $this->assign('imagesList', $imagesList);

        $areaMdl = new Area();
        $city = BaseHelper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );
        $this->assign('city',$city);

        $ids = $info['cityId'].','.$info['xianId'].','.$info['townId'];
        $area = Area::where('id','in',$ids)->field('name')->select();
        $str = [];
        foreach ($area as $v) {
            $str[] = $v['name'];
        }
        $this->assign('area',implode('-', $str));

        return $this->view->fetch($this->editView, ['info' => $info]);
    }

    public function editPost(Request $request, $redirect='') {
        $model = model($this->model);

        //save data
        if ($request->isAjax()) {
            $data = $request->param();
            // Update data
            $data['updateDate'] = time();
            $data['updateOper'] = $this->admin->id;
            $data['imgUrl'] = $data['coverImg'];
            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if($result !== false) {
                // 单图
                if (isset($data['imgId']) && !empty($data['imgId'])) {
                    Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages']);
                }
                // 多图
                if (isset($data['imgIds']) && !empty($data['imgIds'])) {
                    foreach ((array)$data['imgIds'] as $key => $item) {
                        Image::where('id', $item)->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                // 详情图
                if (isset($data['detailImgIds']) && !empty($data['detailImgIds'])) {
                    foreach ((array)$data['detailImgIds'] as $detailImgId) {
                        Image::where('id', $detailImgId)->update(['relatedId' => $data['id'], 'relatedTable' => 'Villages']);
                    }
                }

                // Query执行后的操作
                $model->_after_update($data);

                // 写入日志
                $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('编辑成功！', $redirect);
                } else {
                    return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('error !');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        if($id){
            $member = Member::where(['villageId' => $id, 'isDelete' => 2])->select();
            if($member) {
                return $this->error('该村有村民，请先去删除村民！');
            }

            $Villageprogram = \app\admin\model\Villageprogram::where('villageId',$id)->find();
            if($Villageprogram){
                return $this->error('该村已经绑定过小程序账号，无法删除');
            }

            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // TODO 删除图片
                    // 删除村民
                    $resMember = Member::where(['villageId' => $id])->delete();
                    if($resMember === false){
                        Db::rollback();
                        return $this->error('删除村民失败！', 'admin/' . strtolower($this->model) . '/index');
                    }
                    // 删除文章
                    $resArticle = Article::where(['villageId' => $id])->delete();
                    if($resArticle === false){
                        Db::rollback();
                        return $this->error('删除文章失败！', 'admin/' . strtolower($this->model) . '/index');
                    }

                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

}